package com.zhiyun.yycall.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.gzit.adapter.CommonListAdapter;
import com.gzit.utils.AndroidUtils;
import com.zhiyun.trace.TraceActivity;
import com.zhiyun.view.ContactLetterListView;
import com.zhiyun.view.ContactLetterListView.OnTouchingLetterChangedListener;
import com.zhiyun.yycall.R;
import com.zhiyun.yycall.YYCallController;

public class ContactActivity extends TraceActivity {
	private ListAdapter adapter;
	private ListView personList;
	private TextView overlay;
	private ContactLetterListView letterListView;
	private AsyncQueryHandler asyncQuery;
	private static final String NAME = "name", NUMBER = "number",
			SORT_KEY = "sort_key";

	private static final String ANDROID21_SORT_KEY = "phonetic_name";
	private HashMap<String, Integer> alphaIndexer;// 存放存在的汉语拼音首字母和与之对应的列表位置
	private String[] sections;// 存放存在的汉语拼音首字母
	private Handler handler;
	private OverlayThread overlayThread;

	private static String getSortKey() {
		if (android.os.Build.VERSION.SDK_INT < 8) {
			return "phonetic_display_name";
		}

		return SORT_KEY;
	}

	private static class MyAsyncQueryHandler extends AsyncQueryHandler {

		private ListAdapter adapter;

		public MyAsyncQueryHandler(ContentResolver cr, ListAdapter adapter) {
			super(cr);
			this.adapter = adapter;

		}

		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {

			try {
				if (cursor != null && cursor.getCount() > 0) {
					List<ContentValues> list = new ArrayList<ContentValues>();
					cursor.moveToFirst();
					for (int i = 0; i < cursor.getCount(); i++) {
						ContentValues cv = new ContentValues();
						cursor.moveToPosition(i);
						String name = cursor.getString(1);
						String number = cursor.getString(2);
						String sortKey = cursor.getString(3);
						if (number.startsWith("+86")) {
							cv.put(NAME, name);
							cv.put(NUMBER, number.substring(3)); // 去掉+86
							cv.put(SORT_KEY, sortKey);
						} else {
							cv.put(NAME, name);
							cv.put(NUMBER, number);
							cv.put(SORT_KEY, sortKey);
						}
						list.add(cv);
					}
					if (list.size() > 0) {
						adapter.reload(list);
					}
				}
			} finally {
				if (cursor != null && !cursor.isClosed()) {
					cursor.close();
				}

			}
		}

	}

	private class ListAdapter extends CommonListAdapter<ContentValues> {

		public ListAdapter(Context ctx) {
			super(ctx, R.layout.contact_list_item);

		}

		@Override
		protected void render(ContentValues item, View view, int position) {

			TextView alpha = (TextView) view.findViewById(R.id.alpha);
			TextView name = (TextView) view.findViewById(R.id.name);
			TextView number = (TextView) view.findViewById(R.id.number);

			name.setText(item.getAsString(NAME));
			number.setText(item.getAsString(NUMBER));
			String currentStr = getAlpha(item.getAsString(SORT_KEY));
			String previewStr = (position - 1) >= 0 ? getAlpha(this.getItem(
					position - 1).getAsString(SORT_KEY)) : " ";
			if (!previewStr.equals(currentStr)) {
				alpha.setVisibility(View.VISIBLE);
				alpha.setText(currentStr);
			} else {
				alpha.setVisibility(View.GONE);
			}

		}

		public void reload(List<ContentValues> list) {
			super.reload(list);
			alphaIndexer = new HashMap<String, Integer>();
			sections = new String[list.size()];

			for (int i = 0; i < list.size(); i++) {
				// 当前汉语拼音首字母
				String currentStr = getAlpha(list.get(i).getAsString(SORT_KEY));
				// 上一个汉语拼音首字母，如果不存在为“ ”
				String previewStr = (i - 1) >= 0 ? getAlpha(list.get(i - 1)
						.getAsString(SORT_KEY)) : " ";
				if (!previewStr.equals(currentStr)) {
					String name = getAlpha(list.get(i).getAsString(SORT_KEY));
					alphaIndexer.put(name, i);
					sections[i] = name;
				}
			}

		}

	}

	private class LetterListViewListener implements
			OnTouchingLetterChangedListener {

		@Override
		public void onTouchingLetterChanged(final String s) {
			if (alphaIndexer.get(s) != null) {
				int position = alphaIndexer.get(s);
				personList.setSelection(position);
				overlay.setText(sections[position]);
				overlay.setVisibility(View.VISIBLE);
				handler.removeCallbacks(overlayThread);
				// 延迟一秒后执行，让overlay为不可见
				handler.postDelayed(overlayThread, 1000);
			}
		}

	}

	// 设置overlay不可见
	private class OverlayThread implements Runnable {

		@Override
		public void run() {
			overlay.setVisibility(View.GONE);
		}

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contact_activity);

		Log.i("test", android.os.Build.VERSION.SDK);

		adapter = new ListAdapter(this);
		personList = (ListView) findViewById(R.id.list_view);
		personList.setAdapter(adapter);

		letterListView = (ContactLetterListView) findViewById(R.id.contact_letter_listview);
		letterListView
				.setOnTouchingLetterChangedListener(new LetterListViewListener());

		asyncQuery = new MyAsyncQueryHandler(getContentResolver(), adapter);

		alphaIndexer = new HashMap<String, Integer>();
		handler = new Handler();
		overlayThread = new OverlayThread();

		personList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				startCall(((ContentValues) adapter.getItem(position))
						.getAsString(NUMBER));

				trace("call_from_contact");
			}
		});

		View inviteContainer = this.findViewById(R.id.invite_container);
		if (inviteContainer != null) {
			inviteContainer.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					gotoInviteActivity();

				}
			});
		}

	}

	private void startCall(final String targetNo) {

		// 网络不可用，提示用户是否切换到正常拨号形式
		if (!AndroidUtils.System.isNetworkAvailable()) {
			AndroidUtils.Dialog.confirm(this, "云之呼温馨提示",
					"当前网络不可用，是否切换回【系统拨号】模式？",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							YYCallController.startNormalCall(
									ContactActivity.this, targetNo);
							finish();

						}
					});

			return;

		}

		YYCallController.createController(this).startCallback(targetNo);

	}

	@Override
	protected void onResume() {
		super.onResume();
		initOverlay();
		Uri uri = Uri.parse("content://com.android.contacts/data/phones");
		String[] projection = { "_id", "display_name", "data1", getSortKey() };
		asyncQuery.startQuery(0, null, uri, projection, null, null,
				getSortKey() + " COLLATE LOCALIZED asc");

		// String[] projection = { "_id", "display_name", "data1" };
		// asyncQuery.startQuery(0, null, uri, projection, null, null, null);
	}

	// 获得汉语拼音首字母
	private String getAlpha(String str) {
		if (str == null) {
			return "#";
		}

		if (str.trim().length() == 0) {
			return "#";
		}

		char c = str.trim().substring(0, 1).charAt(0);
		// 正则表达式，判断首字母是否是英文字母
		Pattern pattern = Pattern.compile("^[A-Za-z]+$");
		if (pattern.matcher(c + "").matches()) {
			return (c + "").toUpperCase();
		} else {
			return "#";
		}
	}

	// 初始化汉语拼音首字母弹出提示框
	private void initOverlay() {

		LayoutInflater inflater = LayoutInflater.from(this);
		overlay = (TextView) inflater.inflate(R.layout.contact_overlay, null);
		overlay.setVisibility(View.GONE);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
						| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
				PixelFormat.TRANSLUCENT);
		WindowManager windowManager = (WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE);
		windowManager.addView(overlay, lp);

	}

	@Override
	protected void onPause() {
		WindowManager windowManager = (WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE);
		windowManager.removeView(overlay);
		super.onPause();

	}

	private void gotoInviteActivity() {
		Intent intent = new Intent();
		intent.setClass(this, InviteActivity.class);
		this.startActivity(intent);

	}

	@Override
	protected void onStop() {
		super.onStop();

	}
}
